// web socket 连接
import { defineStore } from 'pinia';
import { getStorage } from '../utils/storage';

export const connectUrl = () => {
  // const userId = getStorage('userId');
  // const token = getToken();
  const prefix = getStorage('webSocketUrl');
  // return `${prefix}?roomId=${userId}&token=${token}`;
  return prefix;
};

const useWs = defineStore('ws', {
  state: () => ({
    wsref: null,
    wsUrl: '',
    linkCode: '',
    // 当前房间多少人
    roomCount: 0,
    // 连接状态
    // 0 正在连接
    // 1 连接成功
    // 2 连接失败
    // 3 已断开
    connectStatus: 0,
    // 传递的文件数量
    files: [
      // ...new Array(19).fill({
      //   src: 'http://http://dev98.oa.henanyuexue.com/api/szjctask/alioss/projection/getFile?filePath=projection/b4deef271e5f43a982ed0c5bc19e9cc6/1729072885939.file-1729072885641',
      //   date: '2024-10-16 18:01:26',
      // }),
    ],
  }),
  actions: {
    setWsUrl() {
      this.wsUrl = connectUrl();
    },

    // 连接websocket
    connect() {
      if (!this.wsref) {
        this.wsref = new WebSocket(this.wsUrl);
      }

      setTimeout(() => {
        this.wsInit();
      });
    },

    filePush(file) {
      this.files.push(file);
    },

    clearFile() {
      this.file = [];
    },

    wsInit() {
      // 处理连接打开
      // console.log('this.wsref ====> ', this.wsref);
      this.wsref.onopen = () => {
        this.connectStatus = 1;
        console.log('已连接到 WebSocket 服务器');
      };
      const that = this;
      // 处理接收到的消息
      this.wsref.onmessage = (event) => {
        if (event.data instanceof Blob) {
          // 创建 FileReader 实例
          const reader = new FileReader();
          // 定义 onload 事件处理函数
          reader.onload = function () {
            const text = reader.result;
            const { type, data } = JSON.parse(text);
            console.log('text ===> ', text);
            console.log('data ====>  ', data);
            switch (type) {
              case 'prev':
              case 'next':
                window.electronAPI?.callwsOrder(type);
                break;
              case 'code':
                that.linkCode = data;
                break;
              case 'files':
                // 填充数据
                data.forEach((el, index) => {
                  console.log('that.files ===> ', that.files.length);
                  console.log('that.files ===> ', that.files.length + index);
                  el.id = that.files.length + 1;
                  el.name = '传输资源' + (el.id < 10 ? `0${el.id}` : el.id);
                  that.filePush(el);
                });
                break;
            }
          };
          // 读取 Blob 数据为字符串
          reader.readAsText(event.data);
          return;
        }

        const data = JSON.parse(event.data);
        // 更新页面上的人数显示
        if (data.type === 'roomCount') {
          this.roomCount = data.count;
        }
      };

      // 处理连接关闭
      this.wsref.onclose = () => {
        this.connectStatus = 0;
        console.log('连接已关闭');
        setTimeout(() => {
          that.files = [];
          that.connect();
        });
      };

      // 处理连接错误
      this.wsref.onerror = (error) => {
        this.connectStatus = 2;
        console.error('WebSocket 错误:', error);
      };
    },

    close() {
      console.log('this.wsref ====================>>>>?????????????? ');
      if (this.wsref) {
        console.log('关闭连接');
        this.wsref.send(JSON.stringify({ type: 'close' }));
        this.wsref.close();
        this.wsref = null;
      }
    },
  },
});
export default useWs;
